﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using System.IO;
using Michsky.UI.ModernUIPack;
using UnityEngine.Networking;

public class AppUIManager : MonoBehaviour
{
    #region public member
    [Header("各个面板")]
    public GameObject[] MainOrOwnPanel;
    public GameObject AboutCoderPanel;
    public GameObject SkinPanel;

    [Header("面板中的文本")]
    public Text AboutCoderText;
    public Text SkinPanelTimeShow;

    [Header("最顶部的对象")]
    public GameObject[] MainOrOwnPanelButtonObject;

    [Header("输入文字组件")]
    public InputField ResachField;

    [Header("OwnPanel头像Image组件")]
    public Image headPicture;

    [Header("改变主题色时需变化的对象")]
    public Image[] ThemeChangeColorObject;
    public Image[] Backgrounds;

    [Header("SkinPanel内的根据时间切换主题Toggle")]
    public Toggle ChangeThemeOfTimeToggle;

    [Header("MainPanel")]
    public Scrollbar Scrollbar;
    public GameObject MainPanelContent;
    public GameObject BackTopObject;
    public ModalWindowManager UpdatePanel;

    [Header("AboutPanel")]
    public ModalWindowManager LeaveApp;

    [HideInInspector]
    public List<Text> videoTexts = new List<Text>();

    public static AppUIManager instance;

    [Header("Current Panel")]
    public CurrentPanelType agoPanel = CurrentPanelType.MainPanel;
    public CurrentPanelType currentPanel = CurrentPanelType.MainPanel;

    [Header("UpdatePanel")]
    public Text UpdateProgressInfo;

    [Header("FirstOpenAppInfo")]
    public ModalWindowManager Disclaimer;

    #endregion

    #region private member
    private float currentPanelWaitTime;
    private string currentThemeColor
    {
        get
        {
            return PlayerPrefs.GetString("CurrentThemeColor", "White");
        }
        set
        {
            PlayerPrefs.SetString("CurrentThemeColor", value);
        }
    }
    private string currentChangeThemeToggleState
    {
        get
        {
            return PlayerPrefs.GetString("CurrentChangeThemeToggleState", "true");
        }
        set
        {
            PlayerPrefs.SetString("CurrentChangeThemeToggleState", value);
        }
    }
    private bool canBackTop = false;

    private int canQuit = 0;
    private bool canChangeCanQuitInt = true;

    private static int lastCancelUpdateTime
    {
        get => PlayerPrefs.GetInt("LastCancelUpdateTime", 8);  //默认为一周之外的数
        set => PlayerPrefs.SetInt("LastCancelUpdateTime", value);
    }

    private static int firstOpenApp
    {
        get => PlayerPrefs.GetInt("FirstOpenApp", 0);  //0 is first open app then 1 is next open app.
        set => PlayerPrefs.SetInt("FirstOpenApp", value);
    }
    #endregion



    public enum CurrentPanelType
    {
        MainPanel,
        OwnPanel,
        AboutPanel,
        SkinPanel,
        PlayVideo,
        OpenAContentText
    }


    private void Awake()
    {
        if (instance == null) instance = this;
    }


    private void Start()
    {
        AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
        javaObject.Call<bool>("showToast", "欢迎进入App");

        ChangeThemeOfTimeToggle.isOn = currentChangeThemeToggleState == "true" ? true : false;
        //更新主题色
        ChangeThemeColor(currentThemeColor);

        //更新版本
        Invoke("UpdateSetUp", 1.5F);
    }

    public void ReadOrCancelDisclaimer(bool isReadDisclaimer)
    {
        firstOpenApp = 1;
        Disclaimer.CloseWindow();
        if (isReadDisclaimer) Application.OpenURL("https://www.cnblogs.com/godshadow/p/14899167.html");
    }

    private void UpdateSetUp()
    {
        if (firstOpenApp == 0) Disclaimer.OpenWindow();
        StartCoroutine(GetTxt("https://maxshadow-1305646487.cos.ap-beijing.myqcloud.com/Txt/UpdateInfo.txt", true));
    }

    private IEnumerator GetTxt(string url, bool getHotUpdateVersion)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        yield return request.SendWebRequest();

        if (getHotUpdateVersion)
        {
            if (request.downloadHandler.isDone)
            {
                string[] UpdateVersionStr = request.downloadHandler.text.Split('=');
                //后台更新版本和本地版本不一样，即视为可更新
                if (UpdateVersionStr[1] != Application.version)
                {
                    //弹出更新窗口
                    if(lastCancelUpdateTime != System.DateTime.Now.Day) UpdatePanel.OpenWindow();
                }
            }
        }
    }

    public IEnumerator InstallApk(string apkPath)
    {
        UnityWebRequest request = UnityWebRequest.Get(apkPath);
        request.SendWebRequest();
        UpdateProgressInfo.gameObject.SetActive(true);
        while (!request.downloadHandler.isDone)
        {
            Debug.Log(request.downloadProgress / 1f * 100);
            UpdateProgressInfo.text = $"更新中：{(request.downloadProgress / 1f * 100).ToString("F2")}%";
            yield return 0;
        }
        if (request.downloadHandler.isDone)
        {
            UpdateProgressInfo.gameObject.SetActive(false);

            if (Application.platform == RuntimePlatform.Android)
            {
                string path = Application.persistentDataPath + "/CommercialPromotion.apk";
                File.WriteAllBytes(path, request.downloadHandler.data);

                AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
                bool canInstall = javaObject.Call<bool>("InstallApk", path);
                if (!canInstall) Debug.LogError("无法安装！");
            }
            else
            {
                //将apk写入沙盒目录
                string path = Application.streamingAssetsPath + "/CommercialPromotion.apk";
                File.WriteAllBytes(path, request.downloadHandler.data);
            }
        }
    }

    public void UpdateVersion()
    {
        UpdatePanel.CloseWindow();
        AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
        javaObject.Call<bool>("showToast", "下载中，请稍等");

        StartCoroutine(InstallApk("https://maxshadow-1305646487.cos.ap-beijing.myqcloud.com/Apk/CommercialPromotion.apk"));
    }

    public void CancelUpdate()
    {
        lastCancelUpdateTime = System.DateTime.Now.Day;
    }


    /// <summary>
    /// 当退出搜索框时
    /// </summary>
    public void OnResachEndEdit()
    {
        foreach (Text item in videoTexts)
        {
            if (item.text.Contains(ResachField.text) || ResachField.text.Length == 0 )
                item.transform.parent.gameObject.SetActive(true);
            else if(!item.text.Contains(ResachField.text))
                item.transform.parent.gameObject.SetActive(false);
        } 
    }


    /// <summary>
    /// 退出应用按钮所调用的内容
    /// </summary>
    public void ApplicationQuit()
    {
        LeaveApp.CloseWindow();
        AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
        javaObject.Call<bool>("showToast", "emmm我会更努力的！");
        Invoke("ApplicationQuit_extend", 1.0F);
    }

    private void ApplicationQuit_extend() => Application.Quit();


    public void OpenSkinPanel()
    {
        currentPanel = CurrentPanelType.SkinPanel;
        Tweener tweener_leave = SkinPanel.transform.DOLocalMoveX(0F, 0.5F);
        tweener_leave.OnComplete(() => { agoPanel = CurrentPanelType.SkinPanel; });
    }

    public void LeaveSkinPanel()
    {
        currentPanel = CurrentPanelType.OwnPanel;
        Tweener tweener = SkinPanel.transform.DOLocalMoveX(800F, 0.5F);
        tweener.OnComplete(() => { agoPanel = CurrentPanelType.OwnPanel; });
    }


    /// <summary>
    /// 关于开发者的一些内容
    /// </summary>
    public void AboutCoder()
    {
        currentPanel = CurrentPanelType.AboutPanel;
        Tweener tweener = AboutCoderPanel.transform.DOLocalMoveX(0F, 0.5F);

        tweener.OnComplete(AboutCoder_2);
    }

    /// <summary>
    /// 关于开发者的一些内容，副函数
    /// </summary>
    private void AboutCoder_2()
    {
        agoPanel = CurrentPanelType.AboutPanel;
        string[] userInfos = null;
        if (Application.platform == RuntimePlatform.WindowsEditor ||
                    Application.platform == RuntimePlatform.WindowsPlayer)
            userInfos = File.ReadAllText(Application.streamingAssetsPath + "/UserInfo.txt").Split('\n');
        else if (Application.platform == RuntimePlatform.Android)
            userInfos = File.ReadAllText(Application.persistentDataPath + "/UserInfo.txt").Split('\n');
        foreach (string item in userInfos)
        {
            string[] oneRaw = item.Split('=');
            switch (oneRaw[0])
            {
                case "AboutUser":
                    Tweener tweener = AboutCoderText.DOText(oneRaw[1], 3F);
                    tweener.Restart();
                    break;
            }
        }
        
    }


    /// <summary>
    /// 从关于开发者面板返回
    /// </summary>
    public void LeaveAboutCoderPanel()
    {
        currentPanel = CurrentPanelType.OwnPanel;
        Tweener tweener = AboutCoderPanel.transform.DOLocalMoveX(800F, 0.5F);
        tweener.OnComplete(() => { 
            agoPanel = CurrentPanelType.OwnPanel;
            AboutCoderText.text = "About Me!";
        });
    }


    /// <summary>
    /// 改变主面板或个人面板
    /// </summary>
    /// <param name="clickPanelType">被点击面板的类型</param>
    public void ChangePanelMainOrOwn(string clickPanelType)
    {
        if(clickPanelType == "Main")
        {
            if (MainOrOwnPanelButtonObject[0].GetComponent<Image>().color == new Color(0.027F, 0.513F, 0.992F, 1F)) return;

            canQuit = 0;
            currentPanel = CurrentPanelType.MainPanel;
            MainOrOwnPanelButtonObject[1].GetComponent<Image>().DOColor(Color.gray, 0.3F);
            MainOrOwnPanelButtonObject[0].GetComponent<Image>().DOColor(new Color(0.027F, 0.513F, 0.992F, 1F), 0.3F);
            MainOrOwnPanelButtonObject[1].GetComponentInChildren<Text>().DOColor(Color.gray, 0.3F);
            MainOrOwnPanelButtonObject[0].GetComponentInChildren<Text>().DOColor(new Color(0.027F, 0.513F, 0.992F, 1F), 0.3F);

            MainOrOwnPanel[0].transform.DOLocalMoveX(0F, 0.5F);
            Tweener tweener = MainOrOwnPanel[1].transform.DOLocalMoveX(800F, 0.5F);
            tweener.OnComplete(() => { agoPanel = CurrentPanelType.MainPanel; });

            SkinPanel.transform.DOLocalMoveX(1600F, 0.5F);
            AboutCoderPanel.transform.DOLocalMoveX(1600F, 0.5F);
        }
        else if(clickPanelType == "Own")
        {
            if (MainOrOwnPanelButtonObject[1].GetComponent<Image>().color == new Color(0.027F, 0.513F, 0.992F, 1F)) return;

            canQuit = 0;
            currentPanel = CurrentPanelType.OwnPanel;
            MainOrOwnPanelButtonObject[0].GetComponent<Image>().DOColor(Color.gray, 0.3F);
            MainOrOwnPanelButtonObject[1].GetComponent<Image>().DOColor(new Color(0.027F, 0.513F, 0.992F, 1F), 0.3F);
            MainOrOwnPanelButtonObject[0].GetComponentInChildren<Text>().DOColor(Color.gray, 0.3F);
            MainOrOwnPanelButtonObject[1].GetComponentInChildren<Text>().DOColor(new Color(0.027F, 0.513F, 0.992F, 1F), 0.3F);

            MainOrOwnPanel[0].transform.DOLocalMoveX(-800F, 0.5F);
            Tweener tweener_2 = MainOrOwnPanel[1].transform.DOLocalMoveX(0F, 0.5F);
            tweener_2.OnComplete(() => { agoPanel = CurrentPanelType.OwnPanel; });

            SkinPanel.transform.DOLocalMoveX(800F, 0.5F);
            AboutCoderPanel.transform.DOLocalMoveX(800F, 0.5F);

            headPicture.color = new Color(1, 1, 1, 0.25F);
            Tweener tweener = headPicture.DOFade(1, 2F);
            tweener.Restart();
        }
    }


    public void ChangeThemeColor(string color)
    {
        switch (color)
        {
            case "White":
                currentThemeColor = "White";
                Camera.main.backgroundColor = Color.white;
                foreach (Image item in ThemeChangeColorObject)
                {
                    item.DOColor(Color.white, 1.0F);
                }
                foreach (Image item in Backgrounds)
                {
                    item.DOColor(new Color(0.9568627F, 0.9568627F, 0.9568627F, 1.0F), 1.0F);
                }
                AndroidJavaObject javaObject = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
                javaObject.Call<bool>("showToast", "主题切换成功");
                break;
            case "Black":
                currentThemeColor = "Black";
                Camera.main.backgroundColor = new Color(0.106F, 0.106F, 0.106F, 1.0F);
                foreach (Image item in ThemeChangeColorObject)
                {
                    item.DOColor(new Color(0.157F, 0.157F, 0.157F, 1.0F), 1.0F);
                }
                foreach (Image item in Backgrounds)
                {
                    item.DOColor(new Color(0.106F, 0.106F, 0.106F, 1.0F), 1.0F);
                }
                AndroidJavaObject javaObject_2 = new AndroidJavaObject("com.example.commercialpromotion.UnityToAndroid");
                javaObject_2.Call<bool>("showToast", "主题切换成功");
                break;
        }
    }

    public void ChangeToggleIsOn() => ChangeThemeOfTimeToggle.isOn = false;

    public void BackMainTop() => canBackTop = true;

    //当按下返回按钮时要处理的事情
    private void ReturnPressed()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            switch (currentPanel)
            {
                case CurrentPanelType.MainPanel:
                    //在主页点击返回，第一次提示，第二次退出app
                    if (canChangeCanQuitInt)
                    {
                        Invoke("AddQuit", 0.8F);
                    }
                    MainOrOwnPanel[0].transform.Find("QuitInfo").GetComponent<NotificationManager>().OpenNotification();
                    break;
                case CurrentPanelType.OwnPanel:
                    ChangePanelMainOrOwn("Main");
                    break;
                case CurrentPanelType.AboutPanel:
                    LeaveAboutCoderPanel();
                    break;
                case CurrentPanelType.SkinPanel:
                    LeaveSkinPanel();
                    break;
                case CurrentPanelType.PlayVideo:
                    DragEvent_Video.EndPlayVideo();
                    break;
                case CurrentPanelType.OpenAContentText:
                    DragEvent_Text.EndContentText();
                    break;
            }
        }
    }

    private void AddQuit()
    {
        canQuit++;
        canChangeCanQuitInt = true;
        if(canQuit >= 2)
        {
            Application.Quit();
            Debug.Log("Quiting");
        }
    }

    private void Update()
    {
        //自动退出程序功能
        //因为是用游戏引擎开发的app，所以如果长时间使用会导致手机发热
        //这里判断如果用户长时间在一个界面不动，则退出程序
        if(agoPanel == currentPanel)
        {
            currentPanelWaitTime += Time.deltaTime;
            if(currentPanelWaitTime > 360F && currentPanel != CurrentPanelType.PlayVideo)
            {
                ApplicationQuit();
            }
        }
        else
        {
            currentPanelWaitTime = 0F;
        }

        SkinPanelTimeShow.text = $"CurrentTime:{System.DateTime.Now}";

        currentChangeThemeToggleState = ChangeThemeOfTimeToggle.isOn == true ? "true" : "false";

        //根据时间自动切换主题色
        if (ChangeThemeOfTimeToggle.isOn)
        {
            if (System.DateTime.Now.Hour < 7F || System.DateTime.Now.Hour > 19F)
            {
                if (currentThemeColor != "Black")
                    ChangeThemeColor("Black");
            }
            else
            {
                if (currentThemeColor != "White")
                    ChangeThemeColor("White");
            }
        }

        //回到顶部按钮
        if(MainPanelContent.transform.childCount > 0 && BackTopObject)
        {
            if(MainPanelContent.transform.GetChild(0).position.y > VideoComponentExtend.rangePos[0].position.y)
            {
                BackTopObject.SetActive(true);
            }
            else
            {
                BackTopObject.SetActive(false);
            }
        }
        if (canBackTop)
        {
            if(Scrollbar.value != 1.0F)
            {
                Scrollbar.value += Mathf.Clamp(Time.deltaTime * 2F, 0F, 1F);
            }
            else
            {
                canBackTop = false;
            }
        }


        ReturnPressed();
    }
}
